package org.indolphin.platform.auth.controller;

import org.indolphin.platform.auth.handler.CustomWebResponseExceptionTranslator;
import org.indolphin.platform.common.entity.DataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

@RestController
@RequestMapping("/oauth")
public class OAuth2Controller {

    private final WebResponseExceptionTranslator<OAuth2Exception> exceptionTranslator = new CustomWebResponseExceptionTranslator();

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;

    @Autowired
    private TokenStore redisTokenStore;

    @GetMapping("/token")
    public DataResult<Object> getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return DataResult.success(tokenEndpoint.getAccessToken(principal, parameters).getBody());
    }

    @PostMapping("/token")
    public DataResult<Object> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException, HttpRequestMethodNotSupportedException {
        return DataResult.success(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }

    @PostMapping("/check_token")
    public DataResult<Object> checkToken(@RequestParam("token") String value) {
        return DataResult.success(checkTokenEndpoint.checkToken(value));
    }

    @PostMapping("/delete")
    public DataResult<Object> deleteToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);

        System.out.println(token);
        redisTokenStore.removeAccessToken(new DefaultOAuth2AccessToken(token));
        return DataResult.success("123");
    }

    //这里是异常翻译，如果这里不设置，则需要在全局异常处处理
    @ExceptionHandler({Exception.class})
    public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
        return this.exceptionTranslator.translate(e);
    }
}
